package com.smarth.zhizulian.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.smarth.zhizulian.R;
import com.smarth.zhizulian.app.BaseConfig;
import com.smarth.zhizulian.bean.BaseEntity;
import com.smarth.zhizulian.bean.lucky.LuckyShareIncome;
import com.smarth.zhizulian.bean.user.DiscipleIndex;
import com.smarth.zhizulian.entity.EventBean;
import com.smarth.zhizulian.http.KumaHttp;
import com.smarth.zhizulian.http.observer.PageObserver;
import com.smarth.zhizulian.http.observer.ProgressObserver;
import com.smarth.zhizulian.http.utils.RxCompos;

import org.simple.eventbus.EventBus;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;
import okhttp3.ResponseBody;

/**
 * Created by 18865 on 2017/12/30.
 */

public class ShareUtils {
    public static void shareToWechatWebPage(String title, String text, String imageUrl, String url, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(title);
        sp.setText(text);
        sp.setImageUrl(imageUrl);
        sp.setUrl(url);
        sp.setShareType(Platform.SHARE_WEBPAGE);
        Platform wechat = ShareSDK.getPlatform(cn.sharesdk.wechat.friends.Wechat.NAME);
        wechat.setPlatformActionListener(platformActionListener);
        wechat.share(sp);
    }

    public static void shareToWechatWebPage(String title, String text, Bitmap imageData, String url, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(title);
        sp.setText(text);
        sp.setImageData(imageData);
        sp.setUrl(url);
        sp.setShareType(Platform.SHARE_WEBPAGE);
        Platform wechat = ShareSDK.getPlatform(cn.sharesdk.wechat.friends.Wechat.NAME);
        wechat.setPlatformActionListener(platformActionListener);
        wechat.share(sp);
    }

    public static void shareToQQWebPage(Context context, String title, String text, Bitmap imageData, String url, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(title);
        sp.setText(text);
//        sp.setImageData(imageData);
//        sp.setImageUrl("http://img.taopic.com/uploads/allimg/120727/201995-120HG1030762.jpg");
        ACache.get(context).put(BaseConfig.ACache.SHARE_QQ, imageData);
        sp.setImagePath(ACache.get(context).file(BaseConfig.ACache.SHARE_QQ).getPath());
        sp.setTitleUrl(url);
        Platform wechat = ShareSDK.getPlatform(QQ.NAME);
        wechat.setPlatformActionListener(platformActionListener);
        wechat.share(sp);
    }

    public static void shareToMomentWebPage(String title, String text, String imageUrl, String url, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(title);
        sp.setText(text);
        sp.setImageUrl(imageUrl);
        sp.setUrl(url);
        sp.setShareType(Platform.SHARE_WEBPAGE);
        Platform moment = ShareSDK.getPlatform(WechatMoments.NAME);
        moment.setPlatformActionListener(platformActionListener);
        moment.share(sp);
    }

    public static void shareToWechatImage(String imageUrl, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
//        sp.setTitle(title);
//        sp.setText(text);
        sp.setImageUrl(imageUrl);
        sp.setShareType(Platform.SHARE_IMAGE);
        Platform wechat = ShareSDK.getPlatform(cn.sharesdk.wechat.friends.Wechat.NAME);
        wechat.setPlatformActionListener(platformActionListener);
        wechat.share(sp);
    }

    public static void shareToWechatImage(Bitmap image, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setImageData(image);
        sp.setShareType(Platform.SHARE_IMAGE);
        Platform wechat = ShareSDK.getPlatform(cn.sharesdk.wechat.friends.Wechat.NAME);
        wechat.setPlatformActionListener(platformActionListener);
        wechat.share(sp);
    }

    public static void shareToMomentImage(String text, Bitmap image, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setText(text);
        sp.setImageData(image);
        sp.setShareType(Platform.SHARE_IMAGE);
        Platform wechat = ShareSDK.getPlatform(WechatMoments.NAME);
        wechat.setPlatformActionListener(platformActionListener);
        wechat.share(sp);
    }

    public static void shareToQQImage(Context context, Bitmap image, PlatformActionListener platformActionListener) {
        Platform.ShareParams sp = new Platform.ShareParams();
        ACache.get(context).put(BaseConfig.ACache.SHARE_QQ, image);
        sp.setImagePath(ACache.get(context).file(BaseConfig.ACache.SHARE_QQ).getPath());
        Platform qq = ShareSDK.getPlatform(QQ.NAME);
        qq.setPlatformActionListener(platformActionListener);
        qq.share(sp);
    }

    public static void thirdLogin(Platform plat, PlatformActionListener platformActionListener) {
        if (plat == null) {
            return;
        }
        if (plat.isAuthValid()) {
            plat.removeAccount(true);
        }
        plat.setPlatformActionListener(platformActionListener);
        plat.showUser(null);
    }

    public static void shareActivityResult(final Context context, final String money, String qrCode, final String platfrom) {
        KumaHttp.getService().downloadFile(qrCode)
                .compose(RxCompos.<ResponseBody>getHttpCompos())
                .subscribe(new ProgressObserver<ResponseBody>(context, true) {
                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Bitmap qrCodeBitmap = BitmapFactory.decodeStream(responseBody.byteStream());
                        if (qrCodeBitmap != null) {
                            View view = LayoutInflater.from(context).inflate(R.layout.view_activityshare, null);
                            TextView tv_money = view.findViewById(R.id.tv_money);
                            ImageView iv_qrcode = view.findViewById(R.id.iv_qrcode);
                            tv_money.setText(money + "元");
                            iv_qrcode.setImageBitmap(qrCodeBitmap);
                            // validate view.width and view.height
                            view.layout(0, 0, 750, 1334);
                            int measuredWidth = View.MeasureSpec.makeMeasureSpec(750, View.MeasureSpec.EXACTLY);
                            int measuredHeight = View.MeasureSpec.makeMeasureSpec(1334, View.MeasureSpec.EXACTLY);
                            // validate view.measurewidth and view.measureheight
                            view.measure(measuredWidth, measuredHeight);
                            view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

                            Bitmap shareBitmap = Bitmap.createBitmap(
                                    view.getMeasuredWidth(),
                                    view.getMeasuredHeight(),
                                    Bitmap.Config.ARGB_8888);
                            Canvas c = new Canvas(shareBitmap);
                            view.draw(c);
                            if (platfrom.equals(Wechat.NAME)) {
                                shareToWechatImage(shareBitmap, new PlatformActionListener() {
                                    @Override
                                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                                        KumaToast.show(context, "分享完成");
                                    }

                                    @Override
                                    public void onError(Platform platform, int i, Throwable throwable) {
                                        KumaToast.show(context, "分享失败");
                                    }

                                    @Override
                                    public void onCancel(Platform platform, int i) {
                                        KumaToast.show(context, "分享取消");
                                    }
                                });
                            } else if (platfrom.equals(WechatMoments.NAME)) {
                                shareToMomentImage("", shareBitmap, new PlatformActionListener() {
                                    @Override
                                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                                        KumaToast.show(context, "分享完成");
                                    }

                                    @Override
                                    public void onError(Platform platform, int i, Throwable throwable) {
                                        KumaToast.show(context, "分享失败");
                                    }

                                    @Override
                                    public void onCancel(Platform platform, int i) {
                                        KumaToast.show(context, "分享取消");
                                    }
                                });
                            } else {
                                KumaToast.show(context, "未知平台");
                            }
                        } else {
                            KumaToast.show(context, "分享失败");
                        }
                    }
                });
    }

    public static void shareHongBao(final Context context, final String platform) {
        final PlatformActionListener platformActionListener = new SimplePlatformListener(context) {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                super.onComplete(platform, i, hashMap);
                KumaHttp.getService().luckyReback()
                        .compose(RxCompos.getBEAll2LoginCompos())
                        .subscribe(new ProgressObserver<BaseEntity>(context, false) {
                            @Override
                            public void onNext(BaseEntity baseEntity) {
                                EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.REFRESH_HONGBAO, "KumaDialogFactory"), "HongBaoFragment");
                            }
                        });
            }
        };
        KumaHttp.getService().luckyShareIncome()
                .compose(RxCompos.<LuckyShareIncome>getBELoginCompos())
                .subscribe(new ProgressObserver<LuckyShareIncome>(context) {
                    @Override
                    public void onNext(LuckyShareIncome luckyShareIncome) {
                        ShareUtils.shareHongBao(context
                                , MoneyUtils.coin2Money(luckyShareIncome.getLuckyCoinCount())
                                , MoneyUtils.coin2Money(luckyShareIncome.getFriendLuckyCoinCount())
                                , luckyShareIncome.getQrCode()
                                , platform
                                , platformActionListener
                        );
                    }
                });
    }

    public static void shareHongBaoFriend(final Context context, final long id, final String platform, final boolean isReBack) {
        final PlatformActionListener platformActionListener = new SimplePlatformListener(context) {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                super.onComplete(platform, i, hashMap);
                if (isReBack) {
                    KumaHttp.getService().luckyReBackFriend(id)
                            .compose(RxCompos.getBEAll2LoginCompos())
                            .subscribe(new ProgressObserver<BaseEntity>(context, false) {
                                @Override
                                public void onNext(BaseEntity baseEntity) {
                                    EventBus.getDefault().post(new EventBean(BaseConfig.EventCode.REFRESH_HONGBAO, "KumaDialogFactory"), "HongBaoFragment");
                                }
                            });
                }
            }
        };
        KumaHttp.getService().luckyShareIncome()
                .compose(RxCompos.<LuckyShareIncome>getBELoginCompos())
                .subscribe(new ProgressObserver<LuckyShareIncome>(context) {
                    @Override
                    public void onNext(LuckyShareIncome luckyShareIncome) {
                        ShareUtils.shareHongBao(context
                                , MoneyUtils.coin2Money(luckyShareIncome.getLuckyCoinCount())
                                , MoneyUtils.coin2Money(luckyShareIncome.getFriendLuckyCoinCount())
                                , luckyShareIncome.getQrCode()
                                , platform
                                , platformActionListener
                        );
                    }
                });
    }

    private static void shareHongBao(final Context context
            , final String money
            , final String friendMoney
            , String qrCode
            , final String platfrom
            , final PlatformActionListener platformActionListener
    ) {
        KumaHttp.getService().downloadFile(qrCode)
                .compose(RxCompos.<ResponseBody>getHttpCompos())
                .subscribe(new ProgressObserver<ResponseBody>(context, true) {
                    @Override
                    public void onNext(ResponseBody responseBody) {
                        Bitmap qrCodeBitmap = BitmapFactory.decodeStream(responseBody.byteStream());
                        if (qrCodeBitmap != null) {
                            View view = LayoutInflater.from(context).inflate(R.layout.view_hongbao, null);
                            TextView tv_money = view.findViewById(R.id.tv_money);
                            TextView tv_moneyfriend = view.findViewById(R.id.tv_moneyfriend);
                            ImageView iv_qrcode = view.findViewById(R.id.iv_qrcode);
                            tv_money.setText("我已收获红包" + money + "元");
                            tv_moneyfriend.setText("抢得好友红包" + friendMoney + "元");
                            iv_qrcode.setImageBitmap(qrCodeBitmap);
                            // validate view.width and view.height
                            view.layout(0, 0, 750, 1334);
                            int measuredWidth = View.MeasureSpec.makeMeasureSpec(750, View.MeasureSpec.EXACTLY);
                            int measuredHeight = View.MeasureSpec.makeMeasureSpec(1334, View.MeasureSpec.EXACTLY);
                            // validate view.measurewidth and view.measureheight
                            view.measure(measuredWidth, measuredHeight);
                            view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

                            Bitmap shareBitmap = Bitmap.createBitmap(
                                    view.getMeasuredWidth(),
                                    view.getMeasuredHeight(),
                                    Bitmap.Config.ARGB_8888);
                            Canvas c = new Canvas(shareBitmap);
                            view.draw(c);
                            if (platfrom.equals(Wechat.NAME)) {
                                shareToWechatImage(shareBitmap, platformActionListener);
                            } else if (platfrom.equals(WechatMoments.NAME)) {
                                shareToMomentImage("", shareBitmap, platformActionListener);
                            } else if (platfrom.equals(QQ.NAME)) {
                                shareToQQImage(context, shareBitmap, platformActionListener);
                            } else {
                                KumaToast.show(context, "未知平台");
                            }
                        } else {
                            KumaToast.show(context, "分享失败");
                        }
                    }
                });
    }

    /**
     * 收徒，加好友
     */
    public static void shareForAddFriends(final Context context, DiscipleIndex discipleIndex, final String platform) {
        if (platform.equals(Wechat.NAME)) {
            shareToWechatWebPage("[微信红包]红包雨派发中，等你来领取！"
                    , "我正在抢现金红包，真金白银1元就可以提现哦～"
                    , BitmapFactory.decodeResource(context.getResources(), R.drawable.share_wechathongbao)
                    , discipleIndex.getWxShareUrl()
                    , new SimplePlatformListener(context)
            );
        } else if (platform.equals(WechatMoments.NAME)) {
            KumaHttp.getService().downloadFile(discipleIndex.getQrCodeImageUrl())
                    .compose(RxCompos.<ResponseBody>getHttpCompos())
                    .subscribe(new ProgressObserver<ResponseBody>(context, true) {
                        @Override
                        public void onNext(ResponseBody responseBody) {
                            Bitmap qrCodeBitmap = BitmapFactory.decodeStream(responseBody.byteStream());
                            if (qrCodeBitmap != null) {
                                final Bitmap mBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.pengyouquan_bb).copy(Bitmap.Config.ARGB_8888, true);
                                Canvas canvas = new Canvas(mBitmap);
                                int width = mBitmap.getWidth();
                                int height = mBitmap.getHeight();

//                            int qrSize = (int) (0.3453f * width * (1 - 0.0386 * 2));
                                int qrSize = (int) (0.4293 * width);
                                qrCodeBitmap = Bitmap.createScaledBitmap(qrCodeBitmap, qrSize, qrSize, false);
                                Rect qrRect = new Rect();
//                            qrRect.left = (int) (width * 0.328f + (width * 0.3453f * 0.0386f));
//                            qrRect.top = (int) (height * 0.6769f + (width * 0.3453f * 0.0386f));
                                qrRect.left = (int) (width * 0.288f);
                                qrRect.top = (int) (height * 0.3757f);
                                qrRect.right = qrRect.left + qrSize;
                                qrRect.bottom = qrRect.top + qrSize;

                                canvas.drawBitmap(qrCodeBitmap, null, qrRect, null);

                                Platform.ShareParams sp = new Platform.ShareParams();
                                sp.setText("【直租链】分享就能赚钱，每天签到赚钱倍增，天天都有幸运红包一元就可提现，收徒更有30%奖励提成，现在下载注册最高可送66元现金，亲测绝对真实哦");
                                sp.setImageData(mBitmap);
                                sp.setShareType(Platform.SHARE_IMAGE);
                                Platform moment = ShareSDK.getPlatform(WechatMoments.NAME);
                                moment.setPlatformActionListener(new PlatformActionListener() {
                                    @Override
                                    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                                        KumaToast.show(context, "分享完成");
                                    }

                                    @Override
                                    public void onError(Platform platform, int i, Throwable throwable) {
                                        KumaToast.show(context, "分享失败");
                                    }

                                    @Override
                                    public void onCancel(Platform platform, int i) {
                                        KumaToast.show(context, "分享取消");
                                    }
                                });
                                moment.share(sp);

                            } else {
                                KumaToast.show(context, "分享失败");
                            }
                        }
                    });
        } else if (platform.equals(QQ.NAME)) {
            KumaHttp.getService().downloadFile(discipleIndex.getQrCodeImageUrl())
                    .compose(RxCompos.<ResponseBody>getHttpCompos())
                    .subscribe(new ProgressObserver<ResponseBody>(context, true) {
                        @Override
                        public void onNext(ResponseBody responseBody) {
                            Bitmap qrCodeBitmap = BitmapFactory.decodeStream(responseBody.byteStream());
                            if (qrCodeBitmap != null) {
                                View view = LayoutInflater.from(context).inflate(R.layout.view_qrcode, null);
                                ImageView iv_qrcode = view.findViewById(R.id.iv_qrcode);
                                iv_qrcode.setImageBitmap(qrCodeBitmap);
                                // validate view.width and view.height
                                view.layout(0, 0, 750, 1334);
                                int measuredWidth = View.MeasureSpec.makeMeasureSpec(750, View.MeasureSpec.EXACTLY);
                                int measuredHeight = View.MeasureSpec.makeMeasureSpec(1334, View.MeasureSpec.EXACTLY);
                                // validate view.measurewidth and view.measureheight
                                view.measure(measuredWidth, measuredHeight);
                                view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());

                                Bitmap shareBitmap = Bitmap.createBitmap(
                                        view.getMeasuredWidth(),
                                        view.getMeasuredHeight(),
                                        Bitmap.Config.ARGB_8888);
                                Canvas c = new Canvas(shareBitmap);
                                view.draw(c);
                                shareToQQImage(context, shareBitmap, new SimplePlatformListener(context));
                            } else {
                                KumaToast.show(context, "分享失败");
                            }
                        }
                    });
        } else {
            KumaToast.show(context, "未知平台");
        }

    }
}
